package com.common.playing.apps.comm.tools;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * Created by Administrator on 2015/6/29.
 */
public class RSAHelper {
    /**
     * 获取公钥
     * @param key 公钥字段
     * @return
     */
    public static PublicKey getPublicKey(String key) {
        try {
            byte[] keyBytes;
            if (key != null) {
                keyBytes = Base64Util.decode(new String(key));
                X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PublicKey publicKey = keyFactory.generatePublic(keySpec);
                return publicKey;
            }
        }catch (Exception e) {

        }
            return null;
    }

    /**
     * 加密算法
     * @param content 加密内容
     * @param key 公共秘钥
     * @return
     */
    public static String encrypt(String content,PublicKey key){
        String result = null;
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte plaintext[] = content.getBytes("UTF-8");
            byte[] enByte = cipher.doFinal(plaintext);
            result = new String(Base64Util.encode(enByte));
        } catch (Exception e){

        }
        return result;
    }

    /**
     * 加密算法
     * @param content 内容
     * @param key 公共秘钥字段
     * @return
     */
    public static String encrypt(String content,String key){
        PublicKey key_temp = getPublicKey(key);
        return encrypt(content,key_temp);
    }

}
